// pages/statistics/statistics.js
const icons = require('../../utils/icons.js');
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentMonth: '',
        totalExpense: 0,
        totalIncome: 0,
        categories: [],
        activeButton: '支出',
        chartData: [],
        startX: 0,
        moveX: 0,
        chartScrollLeft: 0,
        selectedPoint: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function() {
        const app = getApp();
        const currentMonth = `${app.globalData.currentYear}年${app.globalData.currentMonth}月`;
        this.setData({
            currentMonth: currentMonth,
            month: app.globalData.currentMonth,
            currentYear: app.globalData.currentYear
        });
        this.loadData();
        this.loadChartData();
        this.drawPieChart();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        const app = getApp();
        // 检查年月是否需要更新
        if (this.data.month !== app.globalData.currentMonth ||
            this.data.currentYear !== app.globalData.currentYear) {
            const currentMonth = `${app.globalData.currentYear}年${app.globalData.currentMonth}月`;
            this.setData({
                currentMonth: currentMonth,
                month: app.globalData.currentMonth,
                currentYear: app.globalData.currentYear
            });
        }
        // 无论如何都刷新数据
        this.loadData();
        this.loadChartData();
        this.drawPieChart();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    loadData: function() {
        const records = wx.getStorageSync('records') || [];

        // 获取当前选择月份的年和月
        const currentDate = new Date(this.data.currentMonth.replace('年', '/').replace('月', '/1'));
        const currentYear = currentDate.getFullYear();
        const currentMonth = currentDate.getMonth();

        // 过滤当前月份的记录
        const currentMonthRecords = records.filter(record => {
            const recordDate = new Date(record.date);
            return recordDate.getFullYear() === currentYear &&
                recordDate.getMonth() === currentMonth;
        });

        const { expenseCategoryMap, incomeCategoryMap, totalExpense, totalIncome } =
        this.processRecords(currentMonthRecords);

        this.setData({
            totalExpense: totalExpense.toFixed(2),
            totalIncome: totalIncome.toFixed(2),
            expenseCategories: this.processCategories(expenseCategoryMap, totalExpense),
            incomeCategories: this.processCategories(incomeCategoryMap, totalIncome)
        }, () => {
            this.updateDisplayedCategories();
            this.forceUpdate();
        });

        this.loadChartData();
    },

    updateDisplayedCategories: function() {
        const { activeButton, expenseCategories, incomeCategories } = this.data;
        let categories = activeButton === '支出' ? expenseCategories : incomeCategories;

        // 重新计算总金额
        const total = categories.reduce((sum, category) => sum + parseFloat(category.amount), 0);

        // 重新计算每个类别的百分比
        categories = categories.map(category => ({
            ...category,
            percentage: ((parseFloat(category.amount) / total) * 100).toFixed(2)
        }));

        this.setData({ categories }, () => {
            this.drawPieChart();
        });
    },

    processRecords: function(records) {
        let totalExpense = 0;
        let totalIncome = 0;
        const expenseCategoryMap = {};
        const incomeCategoryMap = {};

        records.forEach(record => {
            const amount = Math.abs(parseFloat(record.amount));
            if (record.amount < 0) {
                totalExpense += amount;
                if (!expenseCategoryMap[record.category]) {
                    expenseCategoryMap[record.category] = {
                        amount: 0,
                        icon: record.icon,
                        count: 0
                    };
                }
                expenseCategoryMap[record.category].amount += amount;
                expenseCategoryMap[record.category].count++;
            } else {
                totalIncome += amount;
                if (!incomeCategoryMap[record.category]) {
                    incomeCategoryMap[record.category] = {
                        amount: 0,
                        icon: record.icon,
                        count: 0
                    };
                }
                incomeCategoryMap[record.category].amount += amount;
                incomeCategoryMap[record.category].count++;
            }
        });

        return { expenseCategoryMap, incomeCategoryMap, totalExpense, totalIncome };
    },

    processCategories: function(categoryMap, total) {
        return Object.keys(categoryMap)
            .map(name => ({
                name,
                amount: categoryMap[name].amount.toFixed(2),
                icon: categoryMap[name].icon,
                percentage: ((categoryMap[name].amount / total) * 100).toFixed(2),
                count: categoryMap[name].count // 添加交易笔数
            }))
            .sort((a, b) => b.amount - a.amount);
    },

    changeMonth: function(e) {
        const app = getApp();
        const date = new Date(e.detail.value);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const currentMonth = `${year}年${month}月`;

        app.updateCurrentDate(year, month);
        this.setData({
            currentMonth: currentMonth,
            month: month,
            currentYear: year
        });
        this.loadData();
        this.loadChartData();
        this.drawPieChart();
    },

    switchAnalysis: function(e) {
        const type = e.currentTarget.dataset.type;
        this.setData({ activeButton: type }, () => {
            this.updateDisplayedCategories();
            this.drawChart();
        });
    },

    drawChart: function() {
        this.drawMainChart();
    },

    drawMainChart: function() {
        const ctx = wx.createCanvasContext('lineChart');
        const { chartData, activeButton } = this.data;
        const width = 1500;
        const height = 200;
        const padding = 40;

        // 清空画布
        ctx.clearRect(0, 0, width, height);

        // 绘制横坐标轴
        ctx.beginPath();
        ctx.moveTo(padding, height - padding);
        ctx.lineTo(width - padding, height - padding);
        ctx.stroke();

        // 计算数据点
        const dataType = activeButton === '支出' ? 'expense' : 'income';
        const maxValue = Math.max(...chartData.map(item => item[dataType]));
        const xStep = (width - 2 * padding) / (chartData.length - 1);
        const yStep = (height - 2 * padding) / maxValue;

        // 制横坐标标签
        ctx.setFontSize(10);
        ctx.setTextAlign('center');
        ctx.setTextBaseline('top');
        chartData.forEach((item, index) => {
            if (index % 5 === 0 || index === chartData.length - 1) { // 每5天显示一个标签
                const x = padding + index * xStep;
                const date = new Date(item.date);
                const label = `${date.getDate()}`;
                ctx.fillText(label, x, height - padding + 5);
            }
        });

        // 动态绘制折线和数据点
        let currentIndex = 0;
        const drawNextSegment = () => {
            if (currentIndex >= chartData.length - 1) {
                this.addClickListener();
                return;
            }

            const startX = padding + currentIndex * xStep;
            const startY = height - padding - chartData[currentIndex][dataType] * yStep;
            const endX = padding + (currentIndex + 1) * xStep;
            const endY = height - padding - chartData[currentIndex + 1][dataType] * yStep;

            // 绘制线段
            ctx.beginPath();
            ctx.moveTo(startX, startY);
            ctx.lineTo(endX, endY);
            ctx.setStrokeStyle('#4CAF50');
            ctx.stroke();

            // 绘制数据点
            ctx.beginPath();
            ctx.arc(startX, startY, 3, 0, 2 * Math.PI);
            ctx.setFillStyle('#4CAF50');
            ctx.fill();

            // 绘制Y值
            if (chartData[currentIndex][dataType] > 0) {
                ctx.setFontSize(10);
                ctx.setTextAlign('left');
                ctx.setTextBaseline('bottom');
                const yValue = chartData[currentIndex][dataType].toFixed(2);
                ctx.fillText(yValue, startX + 5, startY - 5);
            }

            ctx.draw(true);

            // 计算滚动位置
            const scrollViewWidth = wx.getSystemInfoSync().windowWidth - 40;
            const scrollPosition = Math.max(0, endX - scrollViewWidth + padding);

            // 滚动到当前绘制的位置
            this.setData({
                chartScrollLeft: scrollPosition
            });

            currentIndex++;
            setTimeout(drawNextSegment, 50);
        };

        drawNextSegment();
    },

    addClickListener: function() {
        const query = wx.createSelectorQuery();
        query.select('#lineChart')
            .fields({ node: true, size: true })
            .exec((res) => {
                const canvas = res[0].node;
                canvas.width = res[0].width;
                canvas.height = res[0].height;

                canvas.addEventListener('touchstart', this.onCanvasTouch.bind(this));
            });
    },

    onCanvasTouch: function(e) {
        const { chartData, activeButton } = this.data;
        const touch = e.touches[0];
        const canvasOffsetLeft = e.target.offsetLeft;
        const canvasOffsetTop = e.target.offsetTop;
        const x = touch.clientX - canvasOffsetLeft;
        const y = touch.clientY - canvasOffsetTop;

        const width = 900;
        const height = 200;
        const padding = 40;
        const leftPadding = 10; // 为了对齐 Y 轴，左侧需要一些 padding
        const xStep = (width - leftPadding - padding) / (chartData.length - 1);

        const index = Math.round((x - leftPadding) / xStep);
        if (index >= 0 && index < chartData.length) {
            const dataType = activeButton === '支出' ? 'expense' : 'income';
            const selectedPoint = {
                date: chartData[index].date,
                value: chartData[index][dataType]
            };
            this.setData({ selectedPoint });
        }
    },

    loadChartData: function() {
        const records = wx.getStorageSync('records') || [];
        const currentDate = new Date(this.data.currentMonth.replace('年', '/').replace('月', '/1'));
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        const lastDay = new Date(year, month + 1, 0).getDate();

        // 创建一个包含当月所有天的数组
        const chartData = [];
        for (let day = 1; day <= lastDay; day++) {
            chartData.push({
                date: `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
                expense: 0,
                income: 0
            });
        }

        // 填充实际的记录数据
        records.forEach(record => {
            const recordDate = new Date(record.date);
            if (recordDate.getFullYear() === year && recordDate.getMonth() === month) {
                const index = recordDate.getDate() - 1;
                if (record.amount < 0) {
                    chartData[index].expense += Math.abs(parseFloat(record.amount));
                } else {
                    chartData[index].income += parseFloat(record.amount);
                }
            }
        });

        this.setData({ chartData }, () => {
            this.drawChart();
        });
    },

    forceUpdate: function() {
        this.setData({ forceUpdateTrigger: Date.now() });
    },

    touchStart: function(e) {
        this.setData({ startX: e.touches[0].x });
    },

    touchMove: function(e) {
        this.setData({ moveX: e.touches[0].x - this.data.startX });
    },

    touchEnd: function() {
        // 这里可以添加滑动结束后的逻辑，比如更新图表显示的日期范围
        this.setData({ startX: 0, moveX: 0 });
        this.drawChart();
    },

    handleChartScroll: function(e) {
        this.setData({
            chartScrollLeft: e.detail.scrollLeft
        });
    },

    drawPieChart: function() {
        const ctx = wx.createCanvasContext('pieChart');
        const { categories, activeButton } = this.data;
        const width = 300;
        const height = 300;
        const centerX = width / 2;
        const centerY = height / 2;
        const radius = Math.min(width, height) / 2 - 10;

        let total = categories.reduce((sum, category) => sum + parseFloat(category.amount), 0);
        let startAngle = 0;

        categories.forEach((category, index) => {
            const sliceAngle = 2 * Math.PI * category.amount / total;
            const endAngle = startAngle + sliceAngle;

            // 绘制扇形
            ctx.beginPath();
            ctx.moveTo(centerX, centerY);
            ctx.arc(centerX, centerY, radius, startAngle, endAngle);
            ctx.closePath();

            // 设置填充颜色
            ctx.setFillStyle(this.getColor(index));
            ctx.fill();

            // 绘制标签和百分比
            const midAngle = startAngle + sliceAngle / 2;
            const labelRadius = radius * 0.7;
            const labelX = centerX + labelRadius * Math.cos(midAngle);
            const labelY = centerY + labelRadius * Math.sin(midAngle);

            ctx.setFillStyle('#000');
            ctx.setFontSize(10);
            ctx.setTextAlign('center');
            ctx.setTextBaseline('middle');

            // 计算并绘制百分比
            const percentage = ((category.amount / total) * 100).toFixed(1) + '%';
            ctx.fillText(category.name, labelX, labelY - 15);
            ctx.fillText(percentage, labelX, labelY);
            ctx.fillText(`${category.count}笔`, labelX, labelY + 15);

            startAngle = endAngle;
        });

        ctx.draw();
    },

    getColor: function(index) {
        const colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'];
        return colors[index % colors.length];
    }
})